package com.geektime.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class JDBCTemplateUtil {

	private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Autowired
	public JDBCTemplateUtil(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
	}

	public Map<String,Object> queryForMap(String sql, Map paramMap) {
		return namedParameterJdbcTemplate.queryForMap(sql, paramMap);
	}

	public List<Map<String,Object>> queryForList(String sql, Map paramMap) {
		return namedParameterJdbcTemplate.queryForList(sql, paramMap);
	}

	public List<Map<String,Object>> queryForList(String sql, Map paramMap, Integer page, Integer pageSize) {
		if (page != null && pageSize != null) {
			Integer firstResult = (page - 1)*pageSize;
			Integer maxResult = pageSize;
			sql += " limit :firstResult,:maxResult";
			paramMap.put("firstResult", firstResult);
			paramMap.put("maxResult", maxResult);
		}
		return namedParameterJdbcTemplate.queryForList(sql, paramMap);
	}


	/**
	 * sql查询单个字段值，常用于查询count(),sum()
	 *
	 * @param sql
	 * @param parameter
	 * @param elementType
	 * @param <T>         返回字段类型
	 * @return
	 */
	public <T> T querySingleColumn(String sql, Map<String, Object> parameter, Class<T> elementType) {
		List<T> list = namedParameterJdbcTemplate.queryForList(sql, parameter, elementType);
		if (arrayIsEmpty(list)) {
			return null;
		}
		return list.get(0);

	}

	public int updateMap(String sql, Map paramMap) {
		return namedParameterJdbcTemplate.update(sql, paramMap);
	}


	public static boolean arrayIsEmpty(List list){
		if(list == null || list.size()<=0){
			return true;
		}else {
			return false;
		}
	}
}
